package com.cdh.edu.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cdh.edu.entity.Video;
import com.cdh.edu.feign.VodService;
import com.cdh.edu.mapper.VideoMapper;
import com.cdh.edu.service.VideoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author cdh
 * @since 2020-10-20
 */
@Service
public class VideoServiceImpl extends ServiceImpl<VideoMapper, Video> implements VideoService {

    @Autowired
    private VodService vodService;

    // 根据课程id删除小节
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteVideoByCourseId(String courseId) {
        QueryWrapper<Video> videoWrapper = new QueryWrapper<>();
        videoWrapper.eq("course_id",courseId);
        baseMapper.delete(videoWrapper);
    }


    @Override
    public void removeVideo(String id) {
        Video video = baseMapper.selectById(id);
        String videoSourceId = video.getVideoSourceId();
        vodService.removeVideo(videoSourceId);
    }

    @Override
    public void removeVideoByChapterId(String chapterId) {
        QueryWrapper<Video> wrapper = new QueryWrapper<>();
        wrapper.select("video_source_id");
        wrapper.eq("chapter_id", chapterId);

        List<Map<String, Object>> maps = baseMapper.selectMaps(wrapper);
        List<String> videoSourceIdList = this.getSourceList(maps);
        vodService.removeBatch(videoSourceIdList);
    }

    @Override
    public void removeVideoByCourseId(String courseId) {
        QueryWrapper<Video> wrapper = new QueryWrapper<>();
        wrapper.select("video_source_id");
        wrapper.eq("course_id", courseId);

        List<Map<String, Object>> maps = baseMapper.selectMaps(wrapper);
        List<String> videoSourceIdList = this.getSourceList(maps);
        vodService.removeBatch(videoSourceIdList);
    }

    private List<String> getSourceList(List<Map<String, Object>> maps){
        List<String> sourceIdList = new ArrayList<>();
        for (Map<String, Object> map : maps) {
            String videoSourceId = (String) map.get("video_source_id");
            sourceIdList.add(videoSourceId);
        }
        return sourceIdList;
    }
}
